package cn.growthgate.fgo.web;

import java.util.Arrays;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;

import cn.growthgate.fgo.common.Constants;
import cn.growthgate.fgo.entity.Painter;
import cn.growthgate.fgo.service.IPainterService;
import cn.growthgate.fgo.util.StringUtils;
import cn.growthgate.fgo.web.result.JsonResult;
import cn.growthgate.fgo.web.result.TableResult;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author GrowthGate
 * @since 2019-05-24
 */
@Controller
@RequestMapping("/painter")
@RequiresRoles(value = {Constants.ROLE_ADMIN}, logical = Logical.OR)
public class PainterController {

	@Autowired
	private IPainterService painterService;

	@RequestMapping("/list")
	public ModelAndView list() {
		return new ModelAndView("painter/list");
	}

	@ResponseBody
	@RequestMapping("/tableData")
	public TableResult<Painter> tableData(Painter painter, Integer current, Integer size, String orderByField, Boolean isAsc) {
		Wrapper<Painter> wrapper = new EntityWrapper<>();

		if (StringUtils.isNotBlank(painter.getName())) {
			wrapper.like("name", painter.getName());
		}
		if (StringUtils.isNotBlank(painter.getjName())) {
			wrapper.like("jName", painter.getjName());
		}

		Page<Painter> page = painterService.selectPage(current, size, orderByField, isAsc, wrapper);
		return new TableResult<Painter>(page);
	}

	@RequestMapping("/form")
	public ModelAndView form(Long id) {
		Painter entity = painterService.selectById(id);

		return new ModelAndView("painter/form").addObject("entity", entity);
	}

	@ResponseBody
	@RequestMapping("/save")
	public JsonResult save(@Validated Painter painter, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return JsonResult.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
		}
		painterService.insertOrUpdate(painter);
		return JsonResult.ok();
	}

	@ResponseBody
	@RequestMapping("/delete")
	public JsonResult delete(Long[] ids) {
		if (painterService.deleteBatchIds(Arrays.asList(ids))) {
			return JsonResult.ok("删除成功");
		} else {
			return JsonResult.fail("删除失败");
		}
	}

}
